#include "idcplatform.h"
#include "ui_idcplatform.h"
//#include "xlsxdocument.h"
//#include "xlsxcellrange.h"
//#include "xlsxworkbook.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QAxObject>
#include <QStandardPaths>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>


IDCplatform::IDCplatform(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IDCplatform)
{
    ui->setupUi(this);
    m_urlAddr="http://192.168.8.205:50001/";
    setLayout(ui->gridLayout);

    m_model = new QStandardItemModel();

    QString style = "::section{Background-color:green;}""::section{color:yellow;}";
    ui->tbv_data->horizontalHeader()->setStyleSheet(style);
    QFont font = QFont("微软雅黑", 12);
    ui->tbv_data->horizontalHeader()->setFont(font);
    ui->tbv_data->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tbv_data->setModel(m_model);
    ui->tbv_data->setColumnWidth(0,200);
    ui->tbv_data->setColumnWidth(1,100);
}

IDCplatform::~IDCplatform()
{
    delete ui;
}

void IDCplatform::setPlatFormFlag(QString platformFlag)
{
    ui->label_flag->setText(platformFlag);
}



int IDCplatform::HttpPostFileUpload(const QString p_sUploadDirPath, QString &p_sReturnData)
{
    // 文件
    QFileInfo fileInfo(p_sUploadDirPath);
    QFile *pFile = new QFile(p_sUploadDirPath);
    if(!pFile->open(QIODevice::ReadOnly))
    {
        p_sReturnData="上传文件" + p_sUploadDirPath + "打开失败";
                        return -1;
    }
    //网络请求对象
    QNetworkRequest request;
    //网络请求地址
    QString sRequestUrl = m_urlAddr+"upload-cacti-info";
    request.setUrl(QUrl(sRequestUrl));
    //request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("multipart/form-data"));
    // 发送的数据
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    // 普通字段
    QHttpPart FileID;
    FileID.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"upload\""));
    FileID.setBody(QString("upload").toLatin1());

    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
    QString requestFormat = QString::fromUtf8("form-data;name=%1;filename=%2;").arg("file").arg(fileInfo.fileName());
    //filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(requestFormat));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + fileInfo.fileName() + "\""));
    filePart.setBodyDevice(pFile);

    pFile->setParent(multiPart); //给pFile设置parent，pFile就不需要再delete了

    multiPart->append(FileID);
    multiPart->append(filePart);

    // 网络请求
    QNetworkAccessManager *accessManager = new QNetworkAccessManager();
    QNetworkReply *reply = accessManager->post(request, multiPart);
    multiPart->setParent(reply); // multiPart不需要delete了

    //事件循环
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    // 获取返回的数据

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    p_sReturnData = QString(reply->readAll());
    pFile->close();
    reply->abort();
    accessManager->deleteLater();//不主动释放会在卸载DLL时造成耗时
    accessManager=NULL;

    return statusCode.toInt();
}

void IDCplatform::on_btn_impData_clicked()
{
    QString m_strFileName = QFileDialog::getOpenFileName(this,"打开",QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");  // 获取打开文件地址

    QString respStr;
    int ret = HttpPostFileUpload(m_strFileName,respStr);
    qDebug()<<"上传文件:"<<m_strFileName<<"返回值:"<<ret<<"返回信息："<<respStr;
    if(ret == 200)
        QMessageBox::information(this, tr("提示"), tr("导入成功！"));
    else
        QMessageBox::information(this, tr("提示"), "导入失败！\n"+respStr);
}


void IDCplatform::on_btn_checkData_clicked()
{
    m_netManager = new QNetworkAccessManager(this);          //新建QNetworkAccessManager对象
    connect(m_netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));//关联信号和槽

    QNetworkRequest quest;
    quest.setUrl(QUrl(m_urlAddr+"export-cacti-info")); //包含最新版本软件的下载地址
    //quest.setHeader(QNetworkRequest::UserAgentHeader, "RT-Thread ART");
    m_pReply = m_netManager->get(quest);    //发送get网络请求
}

void IDCplatform::replyFinished(QNetworkReply *reply)
{
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if (statusCode.toInt() != 200)
    {
        QString retStr = QString("下载失败 状态码:%1\n%2").arg(statusCode.toString()).arg(reply->errorString());
        qDebug()<<"下载文件,返回信息："<<retStr;
        QMessageBox::critical(this, "提示",retStr);
        m_netManager->deleteLater();
        reply->deleteLater();
        reply=NULL;
        return;
    }

    QString strCurrentDir = QCoreApplication::applicationDirPath();//当前程序运行路径
    QString m_strFileName = strCurrentDir + "/hostdata.xlsx";

    if (QFile::exists(m_strFileName))//如果文件已经存在，那么删除
    {
        //qDebug()<<"删除旧文件"<<m_strFileName;
        QFile::remove(m_strFileName);
    }

    QFile *m_file = new QFile(m_strFileName);

    if (!m_file->open(QIODevice::ReadWrite))
    {
        QString retStr = "打开文件失败!"+m_strFileName;
        qDebug()<<retStr;
        QMessageBox::critical(this, "提示",retStr);
        m_file->close();
        delete m_file;
        m_file = NULL;
        return;
    }

    m_file->write(reply->readAll());
    m_file->close();
    m_file = NULL;

    m_netManager->deleteLater();
    reply->deleteLater();
    reply=NULL;

    qDebug()<<"下载文件成功！"<<m_strFileName;

    ReadExcel(m_strFileName);
}

void IDCplatform::ReadExcel(QString strFileName)
{
    QAxObject *excel = new QAxObject(this); //建立excel操作对象
    excel->setControl("Excel.Application"); //连接Excel控件
    excel->setProperty("Visible", false); // 显示窗体
    excel->setProperty("DisplayAlerts", false);//显示警告
    QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿
    // QString str = QFileDialog::getOpenFileName(this,"打开",QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");  // 获取打开文件地址
    workbooks->dynamicCall("Open(const QString&)", strFileName);//打开刚才选定的excel

    QAxObject *workbook = excel->querySubObject("ActiveWorkBook");  // 获取当前活动的工作蒲对象
    QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",1);   // 获取工作簿中的第一个工作表对象
    QAxObject *usedRange = worksheet->querySubObject("UsedRange");  // 获取工作表中使用的区域对象

    int rows = usedRange->querySubObject("Rows")->property("Count").toInt();
    int columns = usedRange->querySubObject("Columns")->property("Count").toInt();
    //qDebug() << "row:" << rows << "col:" << columns;

    QVariant var = usedRange->dynamicCall("Value"); //将所有的数据读取到QVariant容器中保存


    delete usedRange;   // 释放内存
    QVariantList array = var.toList();  // 将容器中数据转换为数组,行数据
    workbooks->dynamicCall("Close()"); //关闭工作簿
    excel->dynamicCall("Quit()"); //退出进程

    //QString value,recDate,usrName;
    QStringList header,customerName,discn;

    for (int i=0;i<array.size();i++)
    {
        QList<QStandardItem*> items;
        items.clear();
        QList<QVariant> dataList = array[i].toList();    // 列数据
        for(int j=0;j<dataList.size();j++)
        {
            QString data = dataList[j].toString();
            //qDebug() <<i<<j<<data;
            if(j<4||(j>6&j<19))
            {
                if(i==0)
                    header<<data;
                else
                {
                    if(j==0)
                        customerName<<data;
                    items.append(new QStandardItem(data));
                }
            }
        }
        if(items.size()>0)
            m_model->appendRow(items);
    }
    m_model->setHorizontalHeaderLabels(header);
    ui->tbv_data->setModel(m_model);

    QString strCustomer;
    for(int m=0;m<customerName.length();m++)
    {
        strCustomer= customerName.at(m);
        if(!discn.contains(strCustomer))
        {
            discn.append(strCustomer);
        }
    }
    ui->comb_customer->clear();
    ui->comb_customer->addItems(discn);
    return ;
}
void IDCplatform::on_btn_executeData_clicked()
{
    int tyear = ui->de_selectYearMonth->date().year();
    int tmonth = ui->de_selectYearMonth->date().month();
    QString strCusName = ui->comb_customer->currentText();
//    qDebug()<<tyear<<tmonth<<strCusName;
//    tyear = 2024;
//    tmonth =1;
//    strCusName = "过客";
    if(strCusName.length()==0)
    {
        QMessageBox::critical(this, "提示","公司名称不能为空！");
        return;
    }
    QString paramStr = "年:"+QString::number(tyear)+"\n月:"+QString::number(tmonth)+"\n公司:"+strCusName+"\n\n确认信息是否正确！";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示",paramStr);
    if(result==QMessageBox::No)
        return;

    QJsonObject obj_root;
    obj_root.insert("year",tyear);
    obj_root.insert("month",tmonth);
    obj_root.insert("startAt",0);
    obj_root.insert("endAt",0);

    QJsonArray arr_cus;
    arr_cus.append(strCusName);
    obj_root.insert("hostNames",arr_cus);

    //qDebug()<<obj_root;
    QJsonDocument document=QJsonDocument(obj_root);
    QByteArray postData = document.toJson();// 转换成QByteArray.

    m_executeMgr = new QNetworkAccessManager();
    connect(m_executeMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(executeReplyFinished(QNetworkReply*)));//关联信号和槽
    //设置url
    QString url = m_urlAddr+"do-cacti";
    //设置头信息
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    requestInfo.setRawHeader("Content-Type","multipart/form-data");//服务器要求的数据头部
    requestInfo.setRawHeader("Accept","application/json,*/*;q=0.5");//服务器要求的数据头部

    m_pReply =  m_executeMgr->post(requestInfo,postData);
}

void IDCplatform::executeReplyFinished(QNetworkReply *reply)
{
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    QString retStr;
    if (statusCode != 200)
    {
        retStr = QString("执行失败 状态码:%1\n%2").arg(statusCode.toString()).arg(reply->errorString());
        qDebug() <<retStr;
        QMessageBox::critical(this, "提示",retStr);
        m_executeMgr->deleteLater();
        reply->deleteLater();
        reply=NULL;
        return;
    }
    //请求收到的结果
    QByteArray responseByte = reply->readAll();
    qDebug() << "responseByte:" << responseByte;
    m_executeMgr->deleteLater();
    reply->deleteLater();
    reply=NULL;
    QMessageBox::information(this, "提示","执行成功！");
}
